#define LOG_TAG "SharedBufferClient"

#include <utils/Log.h>
#include <cutils/ashmem.h>
#include <binder/MemoryBase.h>
#include <binder/IServiceManager.h>

#include "../common/ISharedBuffer.h"

int main() {
    sp<IBinder> binder = defaultServiceManager()->getService(String16(SHARED_BUFFER_SERVICE));
    if (binder == NULL) {
        printf("Failed to get service: %s.\n", SHARED_BUFFER_SERVICE);
        return -1;
    }

    sp<ISharedBuffer> service = ISharedBuffer::asInterface(binder);
    if (service == nullptr) {
        return -2;
    }

    {
        sp<SyncBuffer> buffer = service->createBuffer(10 * 1024, "Buffer-Test");
        if (buffer == nullptr) {
            ALOGE("createBuffer failed");
            return -3;
        }
        ALOGD("createBuffer OK");

        ALOGD("buffer->lock()");
        buffer->lock();
        size_t len;
        auto data = buffer_data_cast<BufferData*>(buffer->addr(&len));
        if (data == nullptr) {
            ALOGE("createBuffer failed, no data");
            return -4;
        }

        data->int1 = 0xaabbccdd;
        data->int2 = 12;
        data->int3 = 76;
        data->int4 = 123;

        const char *buff = "Hello, server\0";
        int bufSize = strlen(buff);
        data->payload_size = bufSize;
        memcpy(data->payload, buff, bufSize);

        int ret = service->commitBuffer(true);
        if (ret == OK) {
            ALOGD("commit buff OK.");
        } else {
            ALOGD("commit buff failed.");
        }

        ALOGE("Sleep 20s to unlock");
        sleep(20);

        buffer->unlock();
        ALOGD("buffer->unlock()");

        //service->releaseBuffer();
    }

    ALOGD("Buffer test finished");

    sleep(100);
    return 0;
}
